package com.example.task.controller;

import com.example.task.entity.HttpTask;
import com.example.task.service.TaskService;
import com.example.task.scheduler.TaskScheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class TaskController {

    @Autowired
    private TaskService service;

    @Autowired
    private TaskScheduler scheduler;

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("tasks", service.getAll());
        return "index";
    }

    @GetMapping("/task/new")
    public String newTaskForm(Model model) {
        model.addAttribute("task", new HttpTask());
        return "task_form";
    }

    @PostMapping("/task")
    public String saveTask(@ModelAttribute HttpTask task) {
        service.save(task);
        if (task.isActive()) {
            scheduler.schedule(task);
        }
        return "redirect:/";
    }

    @GetMapping("/task/edit/{id}")
    public String editTaskForm(@PathVariable Long id, Model model) {
        HttpTask task = service.get(id);
        model.addAttribute("task", task);
        return "task_form";
    }

    @GetMapping("/task/delete/{id}")
    public String deleteTask(@PathVariable Long id) {
        service.delete(id);
        return "redirect:/";
    }

    @GetMapping("/task/toggle/{id}")
    public String toggleTask(@PathVariable Long id) {
        HttpTask task = service.get(id);
        task.setActive(!task.isActive());
        service.save(task);
        if (task.isActive()) {
            scheduler.schedule(task);
        } else {
            scheduler.cancel(task.getId());  // 取消调度
        }
        return "redirect:/";
    }

}
